from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.postgres import get_session
from app.db.mongo import db
from app.models import Evaluation, Activity
from app.services.reporting import generate_report_docx


router = APIRouter(prefix="/reports", tags=["reports"])


@router.post("/{evaluation_id}/generate")
async def generate_report(evaluation_id: str, session: AsyncSession = Depends(get_session)):
    ev = await session.get(Evaluation, evaluation_id)
    if not ev:
        raise HTTPException(status_code=404, detail="评估不存在")
    act = await session.get(Activity, ev.activity_id)
    if not act:
        raise HTTPException(status_code=404, detail="关联活动不存在")
    report_doc = await generate_report_docx(session, db, act, ev)
    # 更新评估中的Mongo引用
    ev.report_docx_mongo_id = str(report_doc["_id"])
    await session.flush()
    await session.commit()
    return {
        "report_id": str(report_doc["_id"]),
        "file_url": report_doc["docx"]["file_url"],
    }